package cn.itcast.wushangxiantu.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.itcast.wushangxiantu.UserData.User;
import cn.itcast.wushangxiantu.OkhttpUtil;
import cn.itcast.wushangxiantu.R;
import cn.itcast.wushangxiantu.ToastUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class Logon extends AppCompatActivity implements View.OnClickListener {

    private EditText et_account;
    private TextView tv_password;
    private EditText et_password;
    private TextView tv_password1;
    private EditText et_password1;
    private Button btnLogin;
    private Button btnReturn;
    private Button btnQuit;

    private String password;
    private String userName;
    private String name;
    private TextView tv_name;
    private EditText et_name;
    private TextView tv_CDK;
    private EditText et_CDK;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_logon);
        initView();
    }

    private void initView() {
        et_account = (EditText) findViewById(R.id.et_account);
        tv_password = (TextView) findViewById(R.id.tv_password);
        et_password = (EditText) findViewById(R.id.et_password);
        tv_password1 = (TextView) findViewById(R.id.tv_password1);
        et_password1 = (EditText) findViewById(R.id.et_password1);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        btnReturn = (Button) findViewById(R.id.btnReturn);
        btnQuit = (Button) findViewById(R.id.btnQuit);

        btnLogin.setOnClickListener(this);
        btnReturn.setOnClickListener(this);
        btnQuit.setOnClickListener(this);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_name.setOnClickListener(this);
        et_name = (EditText) findViewById(R.id.et_name);
        et_name.setOnClickListener(this);
        tv_CDK = (TextView) findViewById(R.id.tv_CDK);
        et_CDK = (EditText) findViewById(R.id.et_CDK);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnLogin:
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                if (submit()) {
                    //判断注册信息是否正确
                    userName = et_account.getText().toString().trim();
                    password = et_password.getText().toString().trim();
                    name = et_name.getText().toString().trim();

                    getDate(userName, password, name);
                }
                break;
            case R.id.btnReturn:
                intent = new Intent(getApplicationContext(), Login.class);
                startActivity(intent);
                finish();
                break;
            case R.id.btnQuit:
                finish();
                break;
        }
    }

    private boolean submit() {
        boolean a = true;
        // validate
        String account = et_account.getText().toString().trim();
        String password = et_password.getText().toString().trim();
        String password1 = et_password1.getText().toString().trim();
        String cdk=et_CDK.getText().toString().trim();
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(account + password + password1);
        if (TextUtils.isEmpty(account)) {
            ToastUtil.toast(this,"账号不能为空");
            a = false;
        } else if (TextUtils.isEmpty(password)) {
            ToastUtil.toast(this,"密码不能为空");
            a = false;
        } else if (TextUtils.isEmpty(password1)) {
            ToastUtil.toast(this,"密码不能为空");
            a = false;
        } else if (!(password.equals(password1))) {
            ToastUtil.toast(this,"两次密码不一致");
            et_password.setText("");
            et_password1.setText("");
            a = false;
        }
        if (m.find()) {
            ToastUtil.toast(this,"账号密码不能带有中文");
            a = false;
        }
        String name = et_name.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            ToastUtil.toast(this,"请输入昵称（1-6位）");
            a = false;
        }
        if (account.length()<6) {
            ToastUtil.toast(this,"账号长度过短");
            a = false;
        }
//        if (TextUtils.isEmpty(cdk)) {
//            Toast.makeText(this, "请输入注册码", Toast.LENGTH_SHORT).show();
//            a = false;
//        }
        // TODO validate success, do something
        return a;

    }


    private void getDate(String userName, String passWord, String name) {

        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userNumber=" + userName + "&passWord=" + passWord + "&need=zhuce" + "&Name=" + name+"&cdk="+et_CDK.getText().toString().trim(), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("Logon11111", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("jack", src);
                User user = null;
                try {
                    user = new Gson().fromJson(src, User.class);
                } catch (Exception e) {
                    user = null;
                }
                Message message = new Message();
                message.obj = user;
                Log.v("jack", user.getStw());
                message.what = 1;
                handler.sendMessage(message);
            }
        });
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            switch (message.what) {
                case 1:
                    User user = (User) message.obj;
                    if (null != user) {
                        if (user.getStw().equals("Yes")) {
                            Intent intent = new Intent(getApplicationContext(), Login.class);
                            ToastUtil.toast(Logon.this, "注册成功");
                            //将获取的值赋值，账号，密码，执行状态
                            Login.getUser().setStw(user.getStw());
                            Login.getUser().setUsernumber(et_account.getText().toString());
                            Login.getUser().setPassword(et_password.getText().toString());
                            startActivity(intent);
                            finish();
                        } else if (user.getStw().equals("No1")) {
                            ToastUtil.toast(Logon.this, "账号已存在");
                        } else if (user.getStw().equals("No2")) {
                            ToastUtil.toast(Logon.this, "该昵称已被占用");
                        } else {
                            ToastUtil.toast(Logon.this, "激活码无效");
                        }
                    } else {
                        ToastUtil.toast(Logon.this, "服务器炸了");
                    }
                    break;
            }


            return false;
        }
    });

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }

}